package com.winai.launcher.view.set;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.ks.projectbasictools.utils.LogUtils;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionErrorCode;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionSuccessListener;
import com.winai.launcher.R;
import com.winai.launcher.adapter.WifiAdapter;
import com.winai.launcher.adapter.WifiItemAdapter;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.CommonBean;
import com.winai.launcher.bean.WifiItemBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.LocationConstant;
import com.winai.launcher.manager.DeviceInfoManager;
import com.winai.launcher.manager.NetworkManager;
import com.winai.launcher.manager.WifiAutoConnectManager;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.override.dialog_global.GlobalDialog;
import com.winai.launcher.utils.CollectionUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/11/18 0018
 * 说明：无线网络
 */
public class SetWifiActivity extends BaseActivity {

    @BindView(R.id.cl_refresh)
    ConstraintLayout clRefresh;
    @BindView(R.id.list)
    LRecyclerView mRecyclerView;
    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;

    private Context mContext = this;
    /*变量*/
    private List<CommonBean> commonBeanList = new ArrayList<>();
    private WifiItemAdapter linkedAdapter, unlinkedAdapter;
    private WifiAdapter wifiAdapter = null;

    protected boolean isUpdate = true;//定时刷新列表数据
    private static final int REFRESH_CONN = 100;
    private static final int LINK_TIMEOUT = 101;
    private static final int LAST_WIFI = 102;
    private final long CONNECT_TIMEOUT = 15000;//连接超时时间
    private Handler mHandler = new MyHandler(this);
    private WifiAutoConnectManager wifiAutoConnectManager;
    private long startTime = 0;

    private Animation loadingAnimation;
    private ConnectivityManager connectivityManager;
    //    private boolean consume = true;//仅执行一次，消耗动作参数
//    private WifiItemBean lastWifi = null;//切换WiFi前连接的WiFi对象——切换WiFi时使用
    private GlobalDialog.Builder connectFailDialog;//网络连接失败
    private boolean isRefreshLoading = false;//刷新动画是否在执行

    private static class MyHandler extends Handler {
        private WeakReference<SetWifiActivity> reference;

        MyHandler(SetWifiActivity activity) {
            this.reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SetWifiActivity activity = reference.get();
            switch (msg.what) {
                case REFRESH_CONN:
                    /*获取WiFi列表*/
                    activity.getWifiList();
                    break;
                case LINK_TIMEOUT:
                    if (NetworkManager.getInstance(activity.mContext).getConnectedWifi() == null) {
                        /*activity.dismissLoading();*/
                        WifiItemBean wifiItemBean = (WifiItemBean) msg.obj;
                        activity.connectFailDialog.setOnCancelClickListener((mGlobalDialog, v) -> {
                            Intent intent = new Intent(activity, SetWifiLinkActivity.class);
                            intent.putExtra("titleName", "连接无线网络");
                            intent.putExtra("WifiItemBean", wifiItemBean);
                            activity.startActivity(intent);
                        }).show();
                        // 取消保存，忽略网络，忽略WiFi，忘记网络
                        activity.wifiAutoConnectManager.removeWifiBySsid(wifiItemBean.getWifiName());
                        activity.notifyItemUI(wifiItemBean, WifiItemBean.LinkState.UNLINK);
                        activity.hidingProgressBar();
                    }
                    break;
                case LAST_WIFI://清空此对象
//                    if (activity.lastWifi != null) {
//                        activity.lastWifi = null;
//                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_wifi);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initListener();
        initView();
        //添加数据
        if (!hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)) {
            requestPermission(LocationConstant.RESULT_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
        }
        /*获取WiFi列表*/
        getWifiList();
//        countDownTimer.start();
    }

    private void initObject() {
        DB_Common dbCommon = new DB_Common(mContext);
        dbCommon.add("isFirstOpenApp", "false");

        String titleName = getIntent().getStringExtra("titleName");
        strTitle.setText(titleName);

        WifiManager mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiAutoConnectManager = WifiAutoConnectManager.newInstance(mWifiManager);

        linkedAdapter = new WifiItemAdapter(mContext, "SetWifiActivity");
        unlinkedAdapter = new WifiItemAdapter(mContext, "SetWifiActivity");

        wifiAdapter = new WifiAdapter(mContext, linkedAdapter, unlinkedAdapter);
        LRecyclerViewAdapter mLRecyclerViewAdapter = new LRecyclerViewAdapter(wifiAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadMoreEnabled(false);
        mRecyclerView.setPullRefreshEnabled(false);

        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());

        connectFailDialog = new GlobalDialog.Builder(mContext)
                .setTitle("网络连接失败")
                .setContent("请检查您的网络和密码，重新尝试连接")
                .setCancelText("好的")
                .setCancelAble(false)
                .setCancelGradient(false);
    }

    private void initListener() {
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.LINK_WIFI:
                        LogUtils.i("进入了GlobalPublisher.LINK_WIFI");
                        if (argObj != null) {
                            notifyItemUI((WifiItemBean) argObj, WifiItemBean.LinkState.LINKED);
                        }
                        break;
                    case GlobalPublisher.CHANGE_WIFI:
                        /*获取WiFi列表*/
                        getWifiList();
                        break;
                    case GlobalPublisher.NETWORK_AVAILABLE:
                        DB_Common dbCommon = new DB_Common(mContext);
                        String isFirst = dbCommon.get("isFirstOpenApp");
                        if (!TextUtils.isEmpty(isFirst)) {
                            networkAvailable();
                        }
                        break;
                    case GlobalPublisher.NETWORK_LOST:
                        networkLost();
                        break;
                }
            }
        });
//        linkedAdapter.setItemClickListener((adapter, view, position) -> {
//            WifiItemBean mWifiItemBean = (WifiItemBean) adapter.getData().get(position);
//            if (mWifiItemBean.getLinkStatus().equals(WifiItemBean.LinkState.LINKED)) {
//                new GlobalDialog.Builder(mContext)
//                        .setTitle("是否忽略此网络")
//                        .setContent("忽略此网络后，设备将断开此网络连接，并清空该网络密码！")
//                        .setConfirmText("忽略")
//                        .setCancelText("取消")
//                        .setConfirmGradient(true)
//                        .setCancelAble(true)
//                        .setOnConfirmClickListener((mGlobalDialog, v1) -> {
//                            // 忽略WiFi，忘记网络
//                            wifiAutoConnectManager.removeWifiBySsid(mWifiItemBean.getWifiName());
//                            NetworkManager.getInstance(mContext).setConnectedWifi(null);
//                            GlobalPublisher.Notify(GlobalPublisher.CHANGE_WIFI, 0);
//                        }).show();
//            }
//        });
//        unlinkedAdapter.setItemClickListener((adapter, view, position) -> {
//            WifiItemBean mWifiItemBean = (WifiItemBean) adapter.getData().get(position);
//            switch (mWifiItemBean.getLinkStatus()) {
//                case WifiItemBean.LinkState.SAVED:
//                    //连接中…
//                    notifyItemUI(mWifiItemBean, WifiItemBean.LinkState.LINKING);
//                    // 连接wifi
//                    WifiUtils.withContext(mContext)
//                            .connectWith(mWifiItemBean.getWifiName(), mWifiItemBean.getBSSID(), "")
//                            .setTimeout(15000)
//                            .onConnectionResult(new ConnectionSuccessListener() {
//                                @Override
//                                public void success() {
//                                    notifyItemUI(mWifiItemBean,WifiItemBean.LinkState.LINKED);
//                                }
//
//                                @Override
//                                public void failed(@NonNull ConnectionErrorCode errorCode) {
//                                    linkFailed(mWifiItemBean, errorCode);
//                                }
//                            })
//                            .start();
//                    break;
//                case WifiItemBean.LinkState.UNLINK:
//                    Intent intent = new Intent(mContext, SetWifiLinkActivity.class);
//                    intent.putExtra("titleName", "连接无线网络");
//                    intent.putExtra("WifiItemBean", mWifiItemBean);
//                    mContext.startActivity(intent);
//                    break;
//            }
//        });
    }

    private void linkFailed(WifiItemBean mWifiItemBean, ConnectionErrorCode errorCode) {
        String msg;
        if (errorCode == ConnectionErrorCode.TIMEOUT_OCCURRED) {
            msg = "连接超时，重新尝试连接";
        } else if (errorCode == ConnectionErrorCode.DID_NOT_FIND_NETWORK_BY_SCANNING) {
            msg = "该网络不在范围内，重新尝试连接";
        } else if (errorCode == ConnectionErrorCode.AUTHENTICATION_ERROR_OCCURRED) {
            msg = "身份验证错误，重新尝试连接";
        } else {
            msg = "请检查您的网络和密码，重新尝试连接";
        }
        new GlobalDialog.Builder(mContext)
                .setTitle("网络连接失败")
                .setContent(msg)
                .setCancelText("好的")
                .setCancelAble(true)
                .setCancelGradient(true)
                .setOnCancelClickListener((mGlobalDialog, v) -> {
                    // 取消保存，忽略网络，忽略WiFi，忘记网络
                    wifiAutoConnectManager.removeWifiBySsid(mWifiItemBean.getWifiName());
                    notifyItemUI(mWifiItemBean, WifiItemBean.LinkState.UNLINK);
                }).show();
    }

    /**
     * @desc 网络连接
     */
    private void networkAvailable() {
        // 1、将Item从未连接中移除 2、放到已连接里面
        updateItemFromLinked(true, NetworkManager.getInstance(mContext).getConnectedWifi());
        updateItemFromUnLined(false, NetworkManager.getInstance(mContext).getConnectedWifi());
        //切换网络后上报服务器
        DeviceInfoManager.getInstance(mContext).updateWifiInfo();
        //执行刷新操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!getWifiList()) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * @desc 网络断开
     */
    private void networkLost() {
        // 1、将Item从已连接中移除 2、放到未连接里面
        updateItemFromLinked(false, NetworkManager.getInstance(mContext).getLostWifi());
        updateItemFromUnLined(true, NetworkManager.getInstance(mContext).getLostWifi());

        //执行刷新操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!getWifiList()) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void initView() {
        commonBeanList.add(0, new CommonBean("0", "当前连接网络"));
        commonBeanList.add(1, new CommonBean("1", "选择连接网络"));
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                wifiAdapter.refreshData(commonBeanList);
            }
        });
    }

    public void showProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (!isRefreshLoading) {
                    isRefreshLoading = true;
                    ivRefresh.startAnimation(loadingAnimation);
                }
            }
        });
    }

    public void hidingProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (isRefreshLoading) {
                    ivRefresh.clearAnimation();
                    isRefreshLoading = false;
                }
            }
        });
    }

    /**
     * 说明：获取WiFi列表
     */
    private boolean getWifiList() {
        long ct = System.currentTimeMillis();
        if (ct - startTime < 5000) {
            LogUtils.e("5s内限制Wifi重复扫描");
            return false;
        }
        startTime = ct;

        showProgressBar();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WifiUtils.withContext(mContext).enableWifi();
                WifiUtils.withContext(getApplicationContext()).scanWifi(this::getScanResults).start();
            }

            private void getScanResults(List<ScanResult> scanResults) {
                List<ScanResult> resultList = WifiAutoConnectManager.noSameName(scanResults);//去除重名wifi
                if (!CollectionUtils.isNullOrEmpty(resultList)) {
                } else {
                    LogUtils.e("Wifi：扫描WiFi列表：没有找到Wifi");
                    mRecyclerView.refreshComplete(0);
                }
                hidingProgressBar();
                refreshData(resultList);
            }
        });
        return true;
    }

    /**
     * 说明：刷新WiFi列表数据
     */
    private void refreshData(List<ScanResult> scanResults) {
        //刷新已连接列表
        refreshLinkedList();
        //刷新未连接列表
        refreshUnlinkedList(scanResults);
    }

    /**
     * 说明：刷新已连接的WiFi
     */
    private void refreshLinkedList() {
        //刷新视图
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                List<WifiItemBean> wifiLinkBeanList = new ArrayList<>();//已连接WiFi列表
                if (NetworkManager.getInstance(mContext).getConnectedWifi() != null) {
                    wifiLinkBeanList.add(new WifiItemBean(
                            NetworkManager.getInstance(mContext).getConnectedWifi().getWifiName().replace("\"", "")
                            , NetworkManager.getInstance(mContext).getConnectedWifi().getBSSID()
                            , NetworkManager.getInstance(mContext).getConnectedWifi().getLinkStatus()
                            , NetworkManager.getInstance(mContext).getConnectedWifi().getLevel()
                    ));
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            linkedAdapter.refreshData(wifiLinkBeanList);
                        }
                    });
                } else {

                    linkedAdapter.refreshData(null);
                }
                //添加\移除 Title标题栏——当前连接网络
//                if (commonBeanList.size() < 2) {
//                    commonBeanList.add(0, new CommonBean("0", "当前连接网络"));
//                } else if (NetworkManager.getInstance(mContext).getConnectedWifi() == null && commonBeanList.size() > 1) {
//                    commonBeanList.remove(0);
//                }
//                wifiAdapter.refreshData(commonBeanList);
//                mRecyclerView.refreshComplete(commonBeanList.size());
            }
        });
    }

    /**
     * 说明：刷新未连接的WiFi
     */
    private void refreshUnlinkedList(List<ScanResult> scanResults) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (scanResults != null) {
                    List<WifiItemBean> wifiUnlinkBeanList = new ArrayList<>();//未连接WiFi列表
                    String linkedWifiName = "";
                    if (NetworkManager.getInstance(mContext).getConnectedWifi() != null) {
                        linkedWifiName = NetworkManager.getInstance(mContext).getConnectedWifi().getWifiName().replace("\"", "");
                    }
                    for (ScanResult scanResult : scanResults) {
                        if (!TextUtils.isEmpty(scanResult.SSID) && !scanResult.SSID.equals(linkedWifiName)) {
                            wifiUnlinkBeanList.add(new WifiItemBean(
                                    scanResult.SSID
                                    , scanResult.BSSID
                                    , wifiAutoConnectManager.isExsits(scanResult.SSID) != null
                                    ? WifiItemBean.LinkState.SAVED : WifiItemBean.LinkState.UNLINK
                                    , scanResult.capabilities
                                    , scanResult.level
                            ));
                        }
                        //设置已连接WiFi的强度
                        if (scanResult.SSID.equals(linkedWifiName) && NetworkManager.getInstance(mContext).getConnectedWifi() != null) {
                            NetworkManager.getInstance(mContext).getConnectedWifi().setLevel(scanResult.level);
                        }
                    }
                    unlinkedAdapter.refreshData(wifiUnlinkBeanList);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //置顶
                            Iterator<WifiItemBean> it_b = wifiUnlinkBeanList.iterator();
                            while (it_b.hasNext()) {
                                WifiItemBean bean = it_b.next();
                                if (bean.getLinkStatus().equals(WifiItemBean.LinkState.SAVED)) {
                                    unlinkedAdapter.onTop(bean);
                                    mRecyclerView.scrollToPosition(0);
                                }
                            }
                        }
                    }, 10);
                }
            }
        });
    }

    /**
     * 说明：通知更新item的UI
     *
     * @param mLinkState 更新成哪种状态
     */
    private synchronized void notifyItemUI(WifiItemBean wifiItemBean, String mLinkState) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                LogUtils.v("通知更新Wifi的" + wifiItemBean.getWifiName().replace("\"", "") + "的UI：mLinkState = " + mLinkState);
                if (isLinkedWifi(wifiItemBean)) {
                    for (int position = 0; position < linkedAdapter.getData().size(); position++) {
                        if (linkedAdapter.getData().get(position).getWifiName().replace("\"", "")
                                .equals(wifiItemBean.getWifiName().replace("\"", ""))) {
                            linkedAdapter.getData().get(position).setLinkStatus(mLinkState);
                            linkedAdapter.notifyItemChanged(position);
                            break;
                        }
                    }
                } else {
                    for (int position = 0; position < unlinkedAdapter.getData().size(); position++) {
                        if (unlinkedAdapter.getData().get(position).getWifiName().replace("\"", "")
                                .equals(wifiItemBean.getWifiName().replace("\"", ""))) {
                            unlinkedAdapter.getData().get(position).setLinkStatus(mLinkState);
                            unlinkedAdapter.notifyItemChanged(position);
                            break;
                        }
                    }
                    //置顶
                    if (mLinkState.equals(WifiItemBean.LinkState.SAVED) || mLinkState.equals(WifiItemBean.LinkState.LINKING)) {
                        //置顶
                        unlinkedAdapter.onTop(wifiItemBean);
                        mRecyclerView.scrollToPosition(0);
                    }
                }
            }
        });
    }

    /**
     * 说明：从“当前连接网络”中添加或移除
     */
    private synchronized void updateItemFromLinked(boolean isInsert, WifiItemBean wifiItemBean) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (isInsert) {
                    if (!wifiExistInLinked(wifiItemBean.getWifiName())) {
                        linkedAdapter.getData().add(0, wifiItemBean);
                        linkedAdapter.notifyItemInserted(0);
                    }
                } else {
                    for (int i = 0; i < linkedAdapter.getData().size(); i++) {
                        if (linkedAdapter.getData().get(i).getWifiName().replace("\"", "")
                                .equals(wifiItemBean.getWifiName().replace("\"", ""))) {
                            linkedAdapter.getData().remove(i);
                            //推荐用这个
                            linkedAdapter.notifyItemRemoved(i);
                            // 如果移除的是最后一个，忽略 注意：这里的mDataAdapter.getDataList()不需要-1，因为上面已经-1了
//                    if (i != (linkedAdapter.getData().size())) {
                            linkedAdapter.notifyItemRangeChanged(i
                                    , linkedAdapter.getData().size() - i);
//                    }
                            break;
                        }
                    }
                }
                refreshLinkedList();
            }
        });
    }

    /**
     * 说明：从“选择连接网络”中添加或移除
     */
    private synchronized void updateItemFromUnLined(boolean isInsert, WifiItemBean wifiItemBean) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (isInsert) {
                    if (!wifiExistInUnlinked(wifiItemBean.getWifiName())) {
                        unlinkedAdapter.getData().add(0, wifiItemBean);
                        unlinkedAdapter.notifyItemInserted(0);
                        //置顶
                        if (wifiItemBean.getLinkStatus().equals(WifiItemBean.LinkState.LINKING) ||
                                wifiItemBean.getLinkStatus().equals(WifiItemBean.LinkState.SAVED)) {
                            unlinkedAdapter.onTop(wifiItemBean);
                            mRecyclerView.scrollToPosition(0);
                        }
                    }
                } else {
                    for (int i = 0; i < unlinkedAdapter.getData().size(); i++) {
                        if (unlinkedAdapter.getData().get(i).getWifiName().replace("\"", "")
                                .equals(wifiItemBean.getWifiName().replace("\"", ""))) {
                            unlinkedAdapter.getData().remove(i);
                            //推荐用这个
                            unlinkedAdapter.notifyItemRemoved(i);
                            // 如果移除的是最后一个，忽略 注意：这里的mDataAdapter.getDataList()不需要-1，因为上面已经-1了
//                    if (i != (unlinkedAdapter.getData().size())) {
                            unlinkedAdapter.notifyItemRangeChanged(i
                                    , unlinkedAdapter.getData().size() - i);
//                    }
                            break;
                        }
                    }
                }
            }
        });
    }

    /**
     * 说明：判断WiFi是否已添加到已连接中
     */
    private synchronized boolean wifiExistInLinked(String wifiName) {
        if (linkedAdapter == null || linkedAdapter.getData().size() == 0) {
            return false;
        }
        List<WifiItemBean> dataList = linkedAdapter.getData();
        for (WifiItemBean bean : dataList) {
            if (bean.getWifiName().replace("\"", "")
                    .equals(wifiName.replace("\"", ""))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 说明：判断发现的设备是否已添加到可用设备
     */
    private synchronized boolean wifiExistInUnlinked(String wifiName) {
        if (TextUtils.isEmpty(wifiName) || wifiName.contains("<unknown ssid>")) {
            return true;
        }
        List<WifiItemBean> dataList = unlinkedAdapter.getData();
        for (WifiItemBean bean : dataList) {
            if (bean.getWifiName().replace("\"", "")
                    .equals(wifiName.replace("\"", ""))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 说明：判断参数wifiItemBean是否是已连接的WiFi
     */
    private boolean isLinkedWifi(WifiItemBean wifiItemBean) {
        for (int i = 0; i < linkedAdapter.getData().size(); i++) {
            if (linkedAdapter.getData().get(i).getWifiName().replace("\"", "")
                    .equals(wifiItemBean.getWifiName().replace("\"", ""))) {
                return true;
            }
        }
        return false;
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.cl_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.cl_refresh:
                /*获取WiFi列表*/
                getWifiList();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == LocationConstant.RESULT_LOCATION) {
            if (grantResults.length > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 第一次获取到权限
                    /*获取WiFi列表*/
                    getWifiList();
                } else {
                    // 没有获取到权限，做特殊处理
                    ToastKs.show(mContext, "请打开相关权限！");
                }
            } else {
                // 没有获取到权限，做特殊处理
                ToastKs.show(mContext, "请打开相关权限！");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Constant.RESULT_LINK_WIFI) {
                if (data != null) {
                    WifiItemBean wifiItemBean = data.getParcelableExtra("wifiItemBean");
                    LogUtils.d("返回的wifiItemBean对象 = " + wifiItemBean);
                    if (wifiItemBean != null) {
                        //连接中…
                        notifyItemUI(wifiItemBean, WifiItemBean.LinkState.LINKING);
                        // 连接wifi
                        WifiUtils.withContext(mContext)
                                .connectWith(wifiItemBean.getWifiName(), wifiItemBean.getBSSID(), "")
                                .setTimeout(15000)
                                .onConnectionResult(new ConnectionSuccessListener() {
                                    @Override
                                    public void success() {
                                        notifyItemUI(wifiItemBean,WifiItemBean.LinkState.LINKED);
                                    }

                                    @Override
                                    public void failed(@NonNull ConnectionErrorCode errorCode) {
                                        linkFailed(wifiItemBean, errorCode);
                                    }
                                })
                                .start();
                    }
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isUpdate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isUpdate = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isUpdate = false;
        mHandler.removeCallbacksAndMessages(null);
    }
}
